package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.client.ProductFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.user.client.UserFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/order")
public class OrderApiController {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("auth/trade")
    public Result trade(HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<>();

        //获取用户id
        String userId = AuthContextHolder.getUserId(request);
        //获取用户地址列表
        List<UserAddress> userAddressList = userFeignClient.findUserAddressList(userId);
        //获取购物车选中商品详情
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
        //声明一个订单明细集合
        List<OrderDetail> detailArrayList = new ArrayList<>();

        int totalNum = 0;
        for (CartInfo cartInfo : cartCheckedList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setOrderPrice(cartInfo.getCartPrice());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            orderDetail.setSkuName(cartInfo.getSkuName());


            detailArrayList.add(orderDetail);
            //总件数
            totalNum += cartInfo.getSkuNum();
        }
        //计算总金额
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(detailArrayList);

        //调用计算方法 计算完成自动加入
        orderInfo.sumTotalAmount();

        //  存储数据！
        map.put("userAddressList", userAddressList);
        map.put("detailArrayList", detailArrayList);
        map.put("totalNum", totalNum);
        map.put("totalAmount", orderInfo.getTotalAmount());

        //储存完成后添加一个流水号
        String tradeNo = this.orderService.getTradeNo(userId);
        //        request.setAttribute("tradeNo",tradeNo);
        map.put("tradeNo", tradeNo);

        return Result.ok(map);
    }

    @PostMapping("auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        //获取用户id
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        //获取订单流水号
        String tradeNo = request.getParameter("tradeNo");
        //比较订单流水号
        Boolean result = orderService.checkTradeNo(tradeNo, userId);
        if (!result) {
            return Result.fail().message("不能重复提交订单!");
        }

        //  校验库存系统：
        //声明一个线程集合
        List<CompletableFuture> futureList = new ArrayList<>();
        //声明一个异常信息集合
        List<String> errorList = new ArrayList<>();
        //得到订单流水集合
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        if (!CollectionUtils.isEmpty(orderDetailList)) {
            for (OrderDetail orderDetail : orderDetailList) {
                //多线程验证库存
                CompletableFuture<Void> stockCompletableFuture = CompletableFuture.runAsync(() -> {
                    Boolean res = orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                    if (!res) {
                        errorList.add(orderDetail.getSkuName() + ":\t库存不足!");
                    }
                }, threadPoolExecutor);
                //添加到多线程集合
                futureList.add(stockCompletableFuture);

                CompletableFuture<Void> priceCompletableFuture = CompletableFuture.runAsync(() -> {

                    String msg = "";
                    //验证订单明细
                    BigDecimal orderPrice = orderDetail.getOrderPrice();
                    BigDecimal price = productFeignClient.getSkuPrice(orderDetail.getSkuId());
                    if (orderPrice.compareTo(price) != 0) {
                        String cartKey = RedisConst.USER_KEY_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX;
//                    CartInfo cartInfo = (CartInfo) redisTemplate.opsForHash().get(cartKey, orderDetail.getSkuId().toString());
                        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
                        for (CartInfo cartInfo : cartCheckedList) {
                            redisTemplate.opsForHash().put(cartKey, cartInfo.getSkuId().toString(), cartInfo);
                        }
                        if (orderPrice.compareTo(price) > 0) {
                            msg = "降价:" + orderPrice.subtract(price).abs();
                        } else {
                            msg = "上涨:" + orderPrice.subtract(price).abs();
                        }
                        errorList.add(orderDetail.getSkuName() + msg);
                    }

                }, threadPoolExecutor);
                futureList.add(priceCompletableFuture);
            }
        }
/*        if (!CollectionUtils.isEmpty(orderDetailList)) {
            for (OrderDetail orderDetail : orderDetailList) {
                //  调用远程方法
                Boolean res = this.orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                if (!res) {
                    return Result.fail().message(orderDetail.getSkuName() + ":\t库存不足!");
                }

                //  验证订单明细价格!
                BigDecimal orderPrice = orderDetail.getOrderPrice();
                BigDecimal price = this.productFeignClient.getSkuPrice(orderDetail.getSkuId());
                //  判断
                String msg = "";
                if (orderPrice.compareTo(price) != 0) {
                    if (orderPrice.compareTo(price) > 0) {
                        msg = "降价" + orderPrice.subtract(price).abs();
                        return Result.fail().message(orderDetail.getSkuName() + msg);
                    } else {
                        msg = "上涨" + orderPrice.subtract(price).abs();
                        return Result.fail().message(orderDetail.getSkuName() + msg);
                    }
                }
            }
        }*/
        //  调用服务层方法：
        Long orderId = this.orderService.saveOrderInfo(orderInfo);
        //  删除流水号
        this.orderService.delTradeNo(userId);
        return Result.ok(orderId);
    }

    //  我的订单数据 分页处理，Page 类中有个属性 records
    @GetMapping("/auth/{page}/{limit}")
    public Result getPageList(@PathVariable Long page,
                              @PathVariable Long limit,
                              HttpServletRequest request) {
        //获取用户id
        String userId = AuthContextHolder.getUserId(request);

        //声明page对象
        Page<OrderInfo> orderInfoPage = new Page<>(page, limit);

        IPage iPage = orderService.getOrderList(orderInfoPage, userId);
        return Result.ok(iPage);
    }

    //  根据订单Id 来获取订单对象
    @GetMapping("inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        return orderService.getOrderInfo(orderId);

    }

    //拆单
    @PostMapping("/orderSplit")
    public String orderSplit(HttpServletRequest request) {
        String orderId = request.getParameter("orderId");
        String wareSkuMap = request.getParameter("wareSkuMap");

        List<OrderInfo> subOrderInfoList = orderService.orderSplit(orderId,wareSkuMap);
        //  获取到对应的数据：
        List<Map> mapList = subOrderInfoList.stream().map(orderInfo -> {
            //将orderInfo变为map
            Map map = orderService.initWare(orderInfo);
            return map;
        }).collect(Collectors.toList());

        return JSON.toJSONString(mapList);
    }
}
